<?php
/**
 * 不命名为OAuthUtil，为了防止冲突
 * @link http://weibo.com/1454872824/yrb5t40Bt
 * @version $Id: OAuthUtil_2.php 216 2012-09-05 12:03:56Z horseluke@126.com $
 */
class OAuthUtil_2{

	/**
	 * boundary of multipart
	 * @ignore
	 */
	public static $boundary = '';
	
    /**
     * builds the data one would send in a POST request
     */
    public static function to_postdata( $parameters, $multi = false ) {
    	if( $multi ){
    		return self::build_http_query_multi($parameters);
   		}else{
        	return self::build_http_query($parameters);
    	}
    }
	
	/**
	 * @ignore
	 */
	public static function build_http_query_multi($params) {
		if (!$params) return '';

		uksort($params, 'strcmp');

		$pairs = array();

		self::$boundary = $boundary = uniqid('------------------');
		$MPboundary = '--'.$boundary;
		$endMPboundary = $MPboundary. '--';
		$multipartbody = '';

		foreach ($params as $parameter => $value) {

			if( in_array($parameter, array('pic', 'image')) && $value{0} == '@' ) {
				$url = ltrim( $value, '@' );
				$content = file_get_contents( $url );
				$array = explode( '?', basename( $url ) );
				$filename = $array[0];

				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
				$multipartbody .= "Content-Type: image/unknown\r\n\r\n";
				$multipartbody .= $content. "\r\n";
			} else {
				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
				$multipartbody .= $value."\r\n";
			}

		}
		
		$multipartbody .= $endMPboundary;
		return $multipartbody;
	}
	
    public static function build_http_query($params) {
        if (!$params){
        	return '';
        }elseif(!is_array($params)){
        	return $params;
        }
        
        //value无数组时，采取内置函数进行编码
        if(!self::_check_value_has_arr($params)){
        	return http_build_query($params);
        }

        // Urlencode both keys and values
        $keys = self::urlencode_rfc3986(array_keys($params));
        $values = self::urlencode_rfc3986(array_values($params));
        $params = array_combine($keys, $values);

        // Parameters are sorted by name, using lexicographical byte value ordering.
        // Ref: Spec: 9.1.1 (1)
        //OAuth 2.0无排序要求，忽略
        //uksort($params, 'strcmp');

        $pairs = array();
        foreach ($params as $parameter => $value) {
            if (is_array($value)) {
                // If two or more parameters share the same name, they are sorted by their value
                // Ref: Spec: 9.1.1 (1)
                //OAuth 2.0无排序要求，忽略。
                //natsort($value);
                foreach ($value as $duplicate_value) {
                    $pairs[] = $parameter . '=' . $duplicate_value;
                }
            } else {
                $pairs[] = $parameter . '=' . $value;
            }
        }
        // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
        // Each name-value pair is separated by an '&' character (ASCII code 38)
        return implode('&', $pairs);
    }
    
    public static function _check_value_has_arr($params){
    	if(!is_array($params) || empty($params)){
    		return false;
    	}
    	$has_arr = false;
    	foreach($params as $val){
    		if(is_array($val)){
    			$has_arr = true;
    			break;
    		}
    	}
    	return $has_arr;
    }
    
    public static function urlencode_rfc3986($input) {
        if (is_array($input)) {
            return array_map(array('OAuthUtil_2', 'urlencode_rfc3986'), $input);
        } else if (is_scalar($input)) {
            return str_replace(
                '+',
                ' ',
                str_replace('%7E', '~', rawurlencode($input))
            );
        } else {
            return '';
        }
    }
	
	
	/**
	 * 获取一条URL指令
	 * @param string $url
	 * @param array|string $paramter
	 */
	public static function get_url($url, $paramter = ''){
		if(empty($paramter)){
			return $url;
		}
		if(is_array($paramter)){
			$paramter = self::build_http_query($paramter);
		}
		
		if(strpos($url, '?') === false){
			return $url. '?'. $paramter;
		}else{
			return $url. '&'. $paramter;
		}
	}
	
}